<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="4" style="min-width: 250px">
        <div class="add">
          <el-button @click="handleAddLevel1" style="width: 100%"
            >添加一级分类</el-button
          >
        </div>

        <el-tree
          :data="deptOptions"
          :props="{ label: 'dictName', children: 'children' }"
          :expand-on-click-node="false"
          ref="deptTreeRef"
          node-key="id"
          highlight-current
          :default-expand-all="false"
          show-checkbox
          @check="handleCheckChange"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="edit">
                <el-tooltip content="添加分类" placement="top">
                  <a @click.stop="append(data)">
                    <el-icon><Plus /></el-icon>
                  </a>
                </el-tooltip>
                <el-tooltip content="编辑" placement="top">
                  <a style="margin-left: 8px" @click.stop="handelEdit(data)">
                    <el-icon><Edit /></el-icon>
                  </a>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <a
                    style="margin-left: 8px"
                    @click.stop="handelDelClass(data)"
                  >
                    <el-icon><DeleteFilled /></el-icon>
                  </a>
                </el-tooltip>
              </span>
            </span>
          </template> </el-tree
      ></el-col>
      <el-col :span="20">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="视频名称" prop="videoName">
            <el-input
              v-model="queryParams.model.videoName"
              placeholder="请输入视频名称"
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="queryParams.model.description"
              placeholder="请输入描述"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="small" @click="handleQuery"
              >搜索</el-button
            >
            <el-button size="small" @click="resetQuery">重置</el-button>
            <!-- <el-button type="primary" plain size="small" @click="handleAdd"
              >新增</el-button
            > -->
          </el-form-item>
        </el-form>

        <el-row>
          <el-col :span="24">
            <el-table v-loading="loading" :data="dataList">
              <el-table-column
                label="序号"
                width="50"
                align="center"
                prop="id"
              />
              <el-table-column
                label="缩略图"
                align="center"
                prop="shrinkageChartId"
              >
                <template #default="scope">
                  <el-image
                    style="width: 50px; height: 50px"
                    preview-teleported
                    :src="scope.row.chartList[0]?.path"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="mapImgUrl(scope.row.chartList)"
                    :initial-index="4"
                    fit="cover"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon size="50"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column label="来源" width="50" align="center">
                <template #default="scope">
                  <span v-if="scope.row.fromType == 1" class="el-tag"
                    >后台</span
                  >
                  <span
                    v-if="scope.row.fromType == 0"
                    class="el-tag el-tag--info"
                    >前台</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="视频名称"
                align="center"
                prop="videoName"
              />
              <el-table-column
                label="描述"
                align="center"
                prop="description"
                show-overflow-tooltip
              />
              <el-table-column
                label="备注"
                align="center"
                prop="remark"
                show-overflow-tooltip
              />
              <el-table-column
                label="上传时间"
                align="center"
                prop="createTime"
              />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <!-- {{ scope.row.status == "1" ? "启用" : "禁用" }} -->

                  <div v-if="scope.row.status == 0">
                    <span class="el-tag el-tag--primary">草稿</span>
                  </div>
                  <div v-if="scope.row.status == 1">
                    <span class="el-tag el-tag--warning">审核中</span>
                  </div>
                  <div v-if="scope.row.status == 2">
                    <span class="el-tag el-tag--success">审批通过</span>
                  </div>
                  <div v-if="scope.row.status == 3">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="scope.row.refuseDes"
                      :disabled="!scope.row.refuseDes"
                      placement="top"
                    >
                      <span class="el-tag el-tag--danger">审批驳回</span>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>

              <!-- <el-table-column label="状态" align="center" prop="status" /> -->
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="280"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    >查看详情</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="el-icon-edit"
                    @click="handelStatusChange(scope.row, 2)"
                    :disabled="scope.row.status == 2 || scope.row.status == 3"
                    >通过</el-button
                  >
                  <el-button
                    icon="el-icon-delete"
                    @click="handelStatusChange(scope.row, 3)"
                    link
                    type="primary"
                    :disabled="scope.row.status == 2 || scope.row.status == 3"
                    >驳回</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30]"
          layout="->,total,sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="currentChange"
        />
      </el-col>
    </el-row>

    <!-- 添加分类log框 -->
    <el-dialog
      :title="`${classForm.id ? '编辑' : '新增'}分类`"
      v-model="classdialogVisible"
      width="30%"
      @close="beforeClose1"
    >
      <el-form
        :model="classForm"
        ref="ruleFormRef"
        label-width="120px"
        :rules="rules1"
      >
        <el-form-item label="分类" prop="dictName">
          <el-input v-model.trim="classForm.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input
            :disabled="isEdit"
            v-model.trim="classForm.dictValue"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="排序" prop="dictSequence">
          <el-input
            v-model.number="classForm.dictSequence"
            style="width: 300px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="classdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handelNewClass"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加或修改标准库信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        disabled
      >
        <el-form-item label="视频名称" prop="videoName">
          <el-input
            v-model.trim="form.videoName"
            placeholder="请输入视频名称"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model.trim="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="排序" prop="description">
          <el-input v-model.number="form.sort" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="选择菜单" prop="retrieveTags">
          <el-cascader
            style="width: 500px"
            v-model="form.retrieveTags"
            :options="deptOptions"
            :props="{
              checkStrictly: false,
              label: 'dictName',
              value: 'id',
              children: 'children',
              emitPath: false,
            }"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否上架" prop="remark">
          <el-switch
            v-model="form.shelfStatus"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-select
            style="width: 100%"
            v-model="form.modelLabels"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="输入需要的关键词 回车键添加"
            @remove-tag="handleRemoveTag"
          >
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="缩略图" prop="shrinkageChartFiles">
          <UploadImg
            :uploadId="0"
            @file-uploaded="handleFileUploaded"
            @file-remove="handleRemoveImg"
            :imglist="appFileImages"
            tip="仅允许上传图片文件！"
          />
        </el-form-item>
        <el-form-item label="视频上传" prop="videoFiles">
          <uploadFile
            :uploadId="0"
            @file-uploaded="handleFileUpload"
            @file-remove="handleRemoveFile"
            :imglist="appFiles"
            tip="仅允许上传 .MP4 文件！"
          />
        </el-form-item>

        <el-form-item label="展示范围" prop="dataScope">
          <el-cascader
            v-model="form.dataScope"
            :options="scopeList"
            :props="{
              multiple: false,
              emitPath: false,
              label: 'label',
              value: 'value',
              children: 'children',
            }"
            collapse-tags
            clearable
          />
        </el-form-item>

        <el-form-item label="上传人">
          <el-input v-model="form.uploadBy" style="width: 260px" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-input v-model="form.uploadTime" style="width: 260px" />
        </el-form-item>
      </el-form>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(0)">保存草稿</el-button>
          <el-button type="primary" @click="submitForm(1)">提交审批</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>

<script>
import UploadImg from "@/components/CustomUpload";
import uploadFile from "./cpns/fileUpload.vue";
import {
  queryAPPListRequest2,
  saveKnowledgeRequest,
  deleteKnowledgeRequest,
  updateKnowledgeStatusRequest,
} from "@/api/knowledge/knowledge";
import {
  getTypeListRequest,
  getDeteilImgByIdRequest,
} from "@/api/public/index.js";
import {
  getDickAllTreeListRequest,
  insertModelType,
  updateModelType,
  deleteModelType,
} from "@/api/buildlibrary";
import { rules } from "./rules.js";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import pagination from "@/components/pagination";

export default {
  name: "knowledge",
  components: {
    UploadImg,
    uploadFile,
    pagination,
  },
  data() {
    return {
      //分类规则
      rules: rules,

      rules1: {
        dictName: [
          { required: true, message: "请输入分类", trigger: "change" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "change",
          },
        ],
        dictValue: [
          { required: true, message: "请输入编码", trigger: "change" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 50 个字符",
            trigger: "change",
          },
        ],
      },
      // 遮罩层
      loading: true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库信息表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        model: {
          childIds: [],
        },
        size: 10,
      },

      // 表单参数
      form: {
        videoName: "", //视频名称
        videoFiles: [], //视频文件
        status: 1, //是否启用
        sort: 0, //排序
        shrinkageChartFiles: [], //缩略图文件
        retrieveTags: "", //检索树id
        remark: "", //备注
        description: "", //描述
        dataScope: "", //展示范围
      },
      // 表单校验

      //树结构
      deptOptions: [],
      //存的所有id
      Allids: [],
      //是否添加编辑弹窗
      classdialogVisible: false,
      parentDictValue: null,
      //添加分类的表单
      classForm: {
        dictName: "", //分类名称
        dictValue: "", //编码
        dictType: "", //dictType
        parentId: 0, //父ID
        dictStatus: 0, //状态
        dictSequence: 0, //排序
      },
      //图片文件列表
      appFileImages: [],
      //文件列表
      appFiles: [],
      //当前选择的左侧树id
      currentTreeId: 0,

      isLoading: null,
      //是否编辑状态
      isEdit: false,

      scopeList: [],

      uploadBy: "", //上传人
      uploadTime: "", //上传时间
    };
  },
  created() {
    this.getList();

    this.getTreeList();

    this.getTypeList();
  },
  methods: {
    //获取字典数据
    async getTypeList() {
      //使用promiseall 请求三个字典
      const res = await Promise.all([
        getTypeListRequest({ size: 999, model: { type: 13 } }), //展示范围
        getTypeListRequest({ size: 999, model: { type: 16 } }), //展示范围2
      ]);

      this.scopeList = [...res[0].data.records, ...res[1].data.records];
    },
    //返回图片链接
    mapImgUrl(data) {
      return data.map((item) => {
        return item.path;
      });
    },
    //分页器size事件
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getList();
    },

    //分页器操作
    currentChange(value) {
      this.queryParams.current = value;
      this.getList();
    },
    //映射操作
    mapDict(dict, id) {
      return dict.find((item) => item.id == id)?.value;
    },

    //获取树结构数据
    async getTreeList() {
      const res = await getDickAllTreeListRequest({ level: 5, dictType: 3 });
      this.deptOptions = res.data;
      console.log(res);
    },
    //添加分类方法
    //新建分类方法
    append(row) {
      this.classdialogVisible = true;
      console.log(row);
      this.classForm.dictValue = row.dictValue + (row.children.length + 1);
      this.classForm.dictSequence = row.children.length + 1;
      this.parentDictValue = row.dictValue;
      this.classForm.dictType = row.dictType;
      this.classForm.parentId = row.id;
    },

    /** 查询标准库信息列表 */
    getList() {
      this.loading = true;

      queryAPPListRequest2(this.queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });

      // listLibrary(this.queryParams).then((response) => {
      //   this.libraryList = response.data.records;
      //   this.total = response.data.total;
      //   this.loading = false;
      // });
    },
    handleNodeClick(nodeData) {
      // 递归查找所有父节点
      const parentNodes = this.findParentNodes(nodeData);
      parentNodes.unshift(nodeData.id);
      let ids = parentNodes.reverse();
      console.log(ids);
      console.log(nodeData);
      this.currentTreeId = nodeData.id;
      this.Allids = ids;
      //请求数据
      this.queryParams.model.parentId = nodeData.id;
      this.getList();
    },

    handleCheckChange(data, checkedData) {
      //获取复选框的所有被选择的id
      // console.log(checkedData);
      // 这是选中的节点的key数组
      console.log(checkedData.checkedKeys);
      this.queryParams.model.childIds = checkedData.checkedKeys;
      this.getList();
    },

    //新建顶级分类
    handleAddLevel1() {
      this.classdialogVisible = true;
      this.classForm.dictType = "3";
      this.classForm.parentId = 0;
      this.parentDictValue = null;
    },

    //新建分类提交表单确认方法
    handelNewClass() {
      this.$refs.ruleFormRef.validate(async (valid, fields) => {
        if (valid) {
          let data = {
            ...this.classForm,
          };

          data.dictValue =
            (this.parentDictValue ? this.parentDictValue : "") + data.dictValue;
          console.log(data);
          // return;
          let fun = data.id ? updateModelType : insertModelType;
          const { code } = await fun(data);
          if (code === 200) {
            ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
            this.classdialogVisible = false;
            this.parentDictValue = null;
            this.getTreeList();
          } else {
            ElMessage.error("服务故障，稍后再试");
            this.parentDictValue = null;
          }
        } else {
          console.log("error submit!", fields);
        }
      });
    },
    //编辑左侧菜单
    handelEdit(row) {
      console.log(row);
      this.isEdit = true; //编辑模式
      this.classdialogVisible = true;
      this.classForm.dictName = row.dictName; //分类名称
      this.classForm.dictValue = row.dictValue; //编码
      this.classForm.parentId = row.parentId; //父级名称
      this.classForm.dictType = row.dictType; //类型
      this.classForm.dictStatus = 0; //状态
      this.classForm.id = row.id; //id
      this.classForm.dictSequence = row.dictSequence; //排序
    },
    selectNodeClick(nodeData) {
      console.log(111);
    },
    //删除模型分类事件
    handelDelClass(row) {
      console.log(row);
      let id = row.id;
      // return;
      ElMessageBox.confirm("你确定要删除此分类吗?", "警告", {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const { code } = await deleteModelType({ ids: [id] });
            if (code === 200) {
              ElMessage.success(`删除成功`);
              this.getTreeList();

              this.queryParams = {
                current: 1,
                model: {
                  childIds: [],
                },
                size: 10,
              };
              this.getList();
            } else {
              ElMessage.error(`服务器故障，稍后再试`);
            }
          } catch (error) {}
        })
        .catch(() => {});
    },
    //关闭dlog回调
    beforeClose1() {
      console.log(1123123);
      this.isEdit = false; //退出编辑模式
      //数据初始化
      this.classForm = {
        dictName: "",
        dictValue: "",
        dictType: "",
        parentId: 0,
        dictStatus: 0,
        dictSequence: 0,
      };
    },
    //缩略图图片上传事件
    handleFileUploaded(data) {
      console.log(data);
      switch (data.uploadId) {
        case 0:
          this.form.shrinkageChartFiles = data.fileData;
          break;
      }
    },
    //图片移除事件
    handleRemoveImg(data) {
      console.log(data);
      if (!data.fileData.id) {
        return;
      }
      switch (data.uploadId) {
        case 0:
          this.form.delShrinkageChartFileIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.shrinkageChartFiles = [];
          }
          break;
      }
    },
    //文件移除事件
    handleRemoveFile(data) {
      console.log(data);
      if (!data.fileData.id) {
        return;
      }
      switch (data.uploadId) {
        case 0:
          this.form.delVideoFileIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.videoFiles = [];
          }
          break;
      }
    },
    //文件上传事件
    handleFileUpload(data) {
      console.log(data);
      switch (data.uploadId) {
        case 0:
          this.form.videoFiles = data.fileData;

          break;
      }
    },

    findParentNodes(nodeData) {
      const parentNodes = [];
      let treeref = this.$refs["deptTreeRef"];
      // console.log(nodeData);

      const findParent = (node) => {
        let pid = treeref.getNode(node).parent.data.id || 0;
        // console.log(pid);
        // console.log(treeref.getNode(node).parent.data);
        if (pid !== 0) {
          parentNodes.push(pid);
          findParent(treeref.getNode(node).parent.data);
        }
      };
      findParent(nodeData);
      return parentNodes;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoName: "", //视频名称
        videoFiles: [], //视频文件
        status: 1, //是否启用
        sort: 0, //排序
        shrinkageChartFiles: [], //缩略图文件
        retrieveTags: "", //检索树id
        remark: "", //备注
        description: "", //描述
        dataScope: "", //展示范围
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = { current: 1, model: {}, size: 10 };
      // this.$refs.deptTreeRef
      //取消所有 el-tree的选中状态
      this.$refs["deptTreeRef"].setCheckedKeys([]);
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.sort = 0;
      this.open = true;
      this.title = "添加知识库信息";
      this.appFileImages = [];
      this.appFiles = [];
    },
    //关闭对话框之后的回调
    closeDialog() {
      this.appFileImages = [];
      this.appFiles = [];
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      this.form.id = row.id;
      this.form.videoName = row.videoName;
      this.form.status = row.status;
      this.form.retrieveTags = parseInt(row.retrieveTags);
      this.form.description = row.description;
      this.form.remark = row.remark;
      this.form.sort = row.sort;
      this.form.shelfStatus = row.shelfStatus;
      this.form.dataScope = row.dataScope.toString();
      this.form.uploadBy = row.createBy; //上传人
      this.form.uploadTime = row.createTime; //上传时间
      this.form.modelLabels = row.modelLabels
        ? row.modelLabels.map((item) => {
            return item.label;
          })
        : [];

      this.form.delShrinkageChartFileIds = []; //删除的封面图片ID集合
      this.form.delVideoFileIds = []; //删除的视频文件ID集合

      this.form.shrinkageChartFiles = 1;
      this.form.videoFiles = 1;

      this.open = true;
      this.title = "查看知识库信息";

      this.appFileImages = row.chartList.map((item) => {
        return {
          id: item.id,
          url: item.path,
        };
      });

      this.appFiles = row.fileList;
    },

    //审批通过和驳回  2通过 3 驳回
    handelStatusChange(row, state) {
      if (state === 2) {
        ElMessageBox.confirm("确定要审核通过吗?", "提示", {
          confirmButtonText: "确认通过",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              const { code } = await updateKnowledgeStatusRequest({
                id: row.id,
                status: state,
              });
              if (code === 200) {
                ElMessage.success(`操作成功`);
                this.getList();
              } else {
                ElMessage.error(`服务器故障，稍后再试`);
              }
            } catch (error) {}
          })
          .catch(() => {});
      }

      if (state === 3) {
        ElMessageBox.prompt("拒绝原因", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,

          inputErrorMessage: "拒绝原因不能为空",
        })
          .then(async ({ value }) => {
            const { code } = await updateKnowledgeStatusRequest({
              id: row.id,
              status: state,
              refuseDes: value,
            });
            if (code === 200) {
              ElMessage.success(`操作成功`);
              this.getList();
            } else {
              ElMessage.error(`服务器故障，稍后再试`);
            }
          })
          .catch(() => {});
      }
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-row) {
  flex-wrap: nowrap;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .edit {
    display: none;
  }
  &:hover {
    // display: block;
    // background-color: red;
    .edit {
      display: block;
    }
  }
}
// .avatar-uploader-icon {
//   width: 100px;
//   height: 100px;
// }
// :deep(.el-upload-list__item) {
//   width: 400px;
// }
</style>
